package cn.com.ry.framework.linklog.configcenter.apollo;

import cn.com.ry.framework.linklog.logging.LinkLogSystem;
import cn.com.ry.framework.linklog.util.LinkLogSwitch;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

public class LinkLogApollo implements InitializingBean {


    private static final Logger logger = LoggerFactory.getLogger(LinkLogApollo.class);

    private static final String accessLogKey = "linklog.accesslog";

    /**
     * 刷新的namespace的名字：linkLog.properties
     *
     * @param changeEvent
     */
    @ApolloConfigChangeListener(value = {"linklog"})
    private void changeLogLevel(ConfigChangeEvent changeEvent) {
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
            logger.info("执行配置变更change-type:{} namespace:{} key:{} old-value:{} new-value:{}", change.getChangeType(), change.getNamespace(), key, change.getOldValue(), change.getNewValue());
            String level = change.getNewValue();
            //重置日志级别，马上生效
            LinkLogSystem.setLevel(key, level);
            logger.info("日志级别变更: logger=" + key + ", level=" + level);
        }
    }

    @Override
    public void afterPropertiesSet() {
        Config loggerConfig = ConfigService.getConfig("linklog");
        for (String key : loggerConfig.getPropertyNames()) {
            if (key != null && key.equalsIgnoreCase(accessLogKey)) {
                String value = loggerConfig.getProperty(key, "true");
                if (value.equalsIgnoreCase("true")) {
                    LinkLogSwitch.setACCESSLOG(true);
                } else if (value.equalsIgnoreCase("false")) {
                    LinkLogSwitch.setACCESSLOG(false);
                }
            }
            String strLevel = loggerConfig.getProperty(key, "info");
            LinkLogSystem.setLevel(key, strLevel);
            logger.debug("日志级别设置: logger=" + key + ", level=" + strLevel.toUpperCase());
        }
    }
}

